<!-- #layout name=default -->
<div id="main" v-cloak>
  <div class="content-fluid">
    <div class="row">
      <div class="col-md-10 col-md-offset-1">
        <div class="page-header">
          <h1 class="title">Template</h1>
          <div class="col-md-4 pull-right" v-if="type == 'list'">
            <div class="row input-group">
              <input
                type="text"
                class="form-control"
                placeholder="Enter your keyword"
                style="height: 32px"
                ref="searchInput"
                @keyup.enter="searchStart"
                v-model="searchKey"
              />
              <div class="input-group-btn">
                <button class="btn btn-default" @click="searchStart">
                  <i class="fa fa-search"></i>Search</button
                >
              </div>
            </div>
          </div>
        </div>
        <div class="clearfix">
          <ul v-if="!searched" class="nav nav-tabs">
            <li
              class="clickable"
              @click="changeType('list')"
              :class="{active:type=='list'}"
            >
              <a href="javascript:;" data-toggle="tab">Public</a>
            </li>
            <li
              @click="changeType('personal')"
              :class="{active:type=='personal'}"
            >
              <a href="javascript:;" data-toggle="tab">Personal</a>
            </li>
          </ul>
          <div
            v-if="searched"
            class="alert alert-block alert-info"
            :class="{ 'alert-info': packages.list.length, 'alert-warning': !packages.list.length }"
          >
            <template v-if="packages.list.length">
              <h4>Search result</h4>
              <p>
                {{Kooboo.text.site.template.weHaveFound + packages.totalCount +
                Kooboo.text.site.template.templateUnit}}
              </p>
            </template>
            <template v-else>
              <h4>{{Kooboo.text.common.sorry}}</h4>
              <p>No template found</p>
            </template>
            <br />
            <p>
              <a
                class="btn"
                href="javascript:;"
                @click="changeKeyword"
                :class="{ blue: packages.list.length, orange: !packages.list.length }"
                >Try other keyword</a
              >
              <a
                class="btn btn-default"
                href="javascript:;"
                @click="clearSearchResult"
                >Return</a
              >
            </p>
          </div>
          <div class="tab-pane" v-show="type=='list'" key="1">
            <div class="row template-list">
              <div
                v-for="($data,index) in packages.list"
                :key="index"
                class="col-sm-6 col-md-3"
              >
                <a
                  href="javascript:;"
                  class="thumbnail"
                  @click="chooseTemplate($data)"
                >
                  <span class="wrapper">
                    <img
                      alt="thumbnail"
                      class="lazy"
                      :data-original="$data.thumbNail"
                      :alt="$data.name"
                      src="/_Admin/Images/logo.png"
                    />
                    <span class="desc">{{$data.description}}</span>
                  </span>
                  <div class="caption">
                    <strong>{{$data.name}}</strong>
                  </div>
                </a>
              </div>
            </div>
            <kb-pager
              :page-nr="packages.pageNr"
              :total-pages="packages.totalPages"
              @change="changePackagesPage"
            ></kb-pager>
          </div>
          <div class="tab-pane" v-show="type=='personal'" key="2">
            <div class="row template-list">
              <div
                v-for="($data,index) in personalPackages.list"
                :key="index"
                class="col-sm-6 col-md-3"
              >
                <a
                  href="javascript:;"
                  @click="chooseTemplate($data)"
                  class="thumbnail"
                >
                  <span class="wrapper">
                    <img
                      alt="thumbnail"
                      class="lazy"
                      :data-original="$data.thumbNail"
                      :alt="$data.name"
                      src="/_Admin/Images/logo.png"
                    />
                    <span class="desc">{{$data.description}}</span>
                  </span>
                  <div class="caption">
                    <strong>{{$data.name}}</strong>
                    <button
                      class="btn btn-xs red pull-right clickable"
                      @click.stop="removePackage($data)"
                      v-kb-tooltip="Kooboo.text.common.remove"
                      ><i class="fa fa-minus"></i
                    ></button>
                    <button
                      class="btn btn-xs blue margin-right-10 pull-right clickable"
                      v-kb-tooltip="Kooboo.text.common.edit"
                      @click.stop="editPackage($data)"
                      ><i class="fa fa-pencil"></i
                    ></button>
                  </div>
                </a>
              </div>
            </div>
            <kb-pager
              :page-nr="personalPackages.pageNr"
              :total-pages="personalPackages.totalPages"
              @change="changePersonalPackagesPage"
            ></kb-pager>
          </div>

          <div
            v-if="(type=='list'&&!packages.list.length)||(type=='personal'&&!personalPackages.list.length) && !searched"
          >
            <div class="well well-lg">
              <h4>{{Kooboo.text.common.sorry}}</h4>
              <p>
                <span>No template available now</span>
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div
    class="modal fade"
    id="editTemplateModal"
    data-backdrop="static"
    data-keyboard="false"
    v-kb-modal="showEditTemplateModal"
  >
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header">
          <button data-dismiss="modal" class="close"
            ><i class="fa fa-close"></i
          ></button>
          <h4 class="modal-title">Edit template</h4>
        </div>
        <div class="modal-body" v-if="showEditTemplateModal">
          <div class="row">
            <div class="col-md-10 col-md-offset-1">
              <div class="form-horizontal">
                <template v-if="editModel">
                  <div class="form-group">
                    <label class="col-md-2 control-label">Site name</label>
                    <div class="col-md-10 row">
                      <div class="col-md-6">
                        <p class="form-control-static">{{editModel.name}}</p>
                      </div>
                    </div>
                  </div>
                  <div class="form-group">
                    <label class="col-md-2 control-label">Tags</label>
                    <div class="col-md-10">
                      <select id="select2_element" multiple style="width: 100%">
                      </select>
                    </div>
                  </div>
                  <div class="form-group">
                    <label class="col-md-2 control-label">Description</label>
                    <div class="col-md-10">
                      <textarea
                        class="form-control autosize"
                        v-model="editModel.description"
                      ></textarea>
                    </div>
                  </div>
                  <div class="form-group">
                    <label class="col-md-2 control-label">Link</label>
                    <div class="col-md-10">
                      <input
                        class="form-control"
                        placeholder="link description"
                        v-model="editModel.link"
                      />
                    </div>
                  </div>
                  <div class="form-group">
                    <label class="col-md-2 control-label">Thumbnails</label>
                    <div class="col-md-10">
                      <div class="fileinput">
                        <span class="btn btn-default btn-file"
                          ><span>Select images</span>
                          <input
                            id="edit_file"
                            type="file"
                            v-kb-upload="{
                            allowMultiple: true,
                            acceptTypes: ['image/bmp','image/png','image/jpg','image/jpeg'],
                            acceptSuffix: ['bmp', 'png', 'jpg', 'jpeg'],
                            callback: uploadImg
                        }"
                          /> </span
                        >&nbsp;
                        <span v-if="!editModel.images.length">
                          <span>Support types: bmp, png, jpg, jpeg.</span>
                          &nbsp;
                          <span>{{Kooboo.text.site.sites.automatically}}</span>
                        </span>
                        <span v-if="editModel.images.length"
                          >Click the image below to select cover image.</span
                        >
                      </div>
                      <div class="file-list img-list">
                        <ul v-if="editModel.images.length">
                          <li
                            v-for="( $data,index) in editModel.images"
                            :key="index"
                            :class="{active: index==editModel.defaultImg}"
                            @click="editModel.defaultImg=index"
                          >
                            <div class="fileinput-new thumbnail">
                              <img
                                :src="$data.data?$data.data:$data"
                                style="width: 100px; height: 100px"
                              />
                            </div>
                            <a
                              href="javascript:;"
                              @click.stop="removeFile($data,index)"
                              v-kb-tooltip="Kooboo.text.common.remove"
                              ><i class="fa fa-remove"></i
                            ></a>
                          </li>
                        </ul>
                      </div>
                    </div>
                  </div>
                </template>
                <div class="form-group">
                  <label for="" class="col-md-2 control-label"
                    >Update package</label
                  >
                  <div class="col-md-10">
                    <div class="fileinput fileinput-new">
                      <span class="btn btn-default btn-file">
                        {{editModel.file?Kooboo.text.common.change:Kooboo.text.common.selectFile}}
                        <input
                          type="file"
                          id="update-package"
                          name="package"
                          v-kb-upload="{
                            allowMultiple: false,
                            acceptTypes: ['application/zip'],
                            acceptSuffix: ['zip'],
                            callback: uploadFile
                        }"
                        />
                      </span>
                      &nbsp;<span v-if="!editModel.file">Select file</span>
                      <span v-if="editModel.file" class="fileinput-filename"
                        >{{editModel.file.name}}</span
                      >
                      <a
                        v-if="editModel.file"
                        class="close"
                        @click="editModel.file=null"
                        ><i class="fa fa-close"></i
                      ></a>
                      <span class="help-block">Accept type: *.zip</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="saveEdit" class="btn green">Save</button>
          <button data-dismiss="modal" class="btn gray">Cancel</button>
        </div>
      </div>
    </div>
  </div>

  <kb-template-modal
    v-model="showTemplateModal"
    :temp-data="templateData"
  ></kb-template-modal>
</div>

<script>
  (function () {
    Kooboo.loadJS([
      "/_Admin/Scripts/lib/select2.min.js",
      "/_Admin/Scripts/components/kbTemplateModal.js",
      "/_Admin/Scripts/components/kbPager.js",
      "/_Admin/Scripts/lib/jquery.textarea_autosize.min.js",
      "/_Admin/Scripts/lib/jquery.lazyload.min.js",
    ]);
    Kooboo.loadCSS(["/_Admin/Styles/select2/select2.css"]);
  })();

  var self = new Vue({
    el: "#main",
    data: function () {
      return {
        types: [
          {
            displayText: Kooboo.text.site.template.public,
            value: "list",
          },
          {
            displayText: Kooboo.text.site.template.personal,
            value: "personal",
          },
        ],
        type: "",
        searchKey: "",
        searched: false,
        packages: { list: [] },
        personalPackages: { list: [] },
        publicTabNeedRefresh: true,
        cachedList: [],
        cachePersonal: [],
        showTemplateModal: false,
        templateData: null,
        showEditTemplateModal: false,
        editModel: {
          id: "",
          name: "",
          isPrivate: false,
          category: null,
          tags: [],
          description: "",
          link: "",
          images: [],
          file: null,
          defaultImg: 0,
        },
      };
    },
    mounted: function () {
      this.$nextTick(function () {
        self.changeType(Kooboo.getQueryString("type") || "list");
      });
    },
    methods: {
      searchStart: function () {
        if (self.searchKey) {
          self.searched = true;
          Kooboo.Template.Search({
            keyword: self.searchKey,
          }).then(function (res) {
            if (res.success) {
              self.packages = res.model;
            }
          });
        } else {
          Kooboo.Template[self.type]().then(function (res) {
            if (res.success) {
              self.searched = false;
              if (self.type == "personal") {
                self.personalPackages = res.model;
              } else {
                self.packages = res.model;
              }
            }
          });
        }
      },
      changeType: function (type) {
        if (self.type !== type) {
          self.type = type;
          if (type == "list") {
            if (!self.packages.list.length || self.publicTabNeedRefresh) {
              Kooboo.Template.list().then(function (res) {
                if (res.success) {
                  self.publicTabNeedRefresh = false;
                  self.packages = res.model;
                  self.cachedList = res.model;
                }
              });
            } else {
              self.packages = self.cachedList;
            }
          } else {
            if (!self.personalPackages.list.length) {
              Kooboo.Template.personal().then(function (res) {
                if (res.success) {
                  self.personalPackages = res.model;
                  self.cachePersonal = res.model;
                }
              });
            } else {
              self.personalPackages = self.cachePersonal;
            }
          }
        }
      },
      changeKeyword: function () {
        this.$refs.searchInput && this.$refs.searchInput.focus();
      },
      clearSearchResult: function () {
        Kooboo.Template.getList().then(function (res) {
          if (res.success) {
            self.searched = false;
            self.searchKey = "";
            self.packages = res.model;
          }
        });
      },
      chooseTemplate: function (item) {
        Kooboo.Template.Get({
          id: item.id,
        }).then(function (res) {
          if (res.success) {
            self.templateData = res.model;
            self.showTemplateModal = true;
          }
        });
      },
      removePackage: function (item) {
        if (confirm(Kooboo.text.confirm.deleteItem)) {
          Kooboo.Template.Delete({
            Id: item.id,
          }).then(function (res) {
            if (res.success) {
              publicTabNeedRefresh = true;
              Kooboo.Template.personal().then(function (res) {
                if (res.success) {
                  self.personalPackages.list = [];
                  self.$nextTick(function () {
                    self.personalPackages = res.model;
                    self.cachePersonal = res.model;
                  });
                }
              });
              window.info.show(Kooboo.text.info.delete.success, true);
            } else {
              window.info.show(Kooboo.text.info.delete.fail, false);
            }
          });
        }
      },
      editPackage: function (item) {
        Kooboo.Template.Get({
          siteId: item.siteId,
          id: item.id,
        }).then(function (res) {
          if (res.success) {
            self.showEditTemplateModal = true;
            self.editModel.id = res.model.id;
            self.editModel.name = res.model.name;
            self.editModel.isPrivate = res.model.isPrivate;
            self.editModel.category = res.model.category;
            self.editModel.tags = res.model.tags
              .split(",")
              .filter(function (m) {
                return !!m;
              });
            self.$nextTick(function () {
              var tags = self.editModel.tags.map(function (item) {
                return {
                  id: item,
                  text: item,
                  selected: true,
                };
              });
              $("#select2_element").select2({
                tags: true,
                tokenSeparators: [",", " ", ";"],
                data: tags,
              });
            });
            self.editModel.description = res.model.description;
            self.editModel.link = res.model.link;
            self.editModel.images = res.model.images;
            self.editModel.file = null;
            var defaultImage = res.model.images.find(function (f) {
              return f.indexOf(res.model.thumbNail) > -1;
            });
            if (defaultImage) {
              self.editModel.defaultImg = res.model.images.indexOf(
                defaultImage
              );
            } else {
              self.editModel.defaultImg = 0;
            }
          }
        });
      },
      changePackagesPage: function (pageNr) {
        window.scrollTo(0, 0);
        if (self.searched) {
          Kooboo.Template.Search({
            keyword: self.searchKey,
            pageNr: pageNr,
          }).then(function (res) {
            if (res.success) {
              self.packages.list = [];
              self.$nextTick(function () {
                self.packages = res.model;
              });
            }
          });
        } else {
          Kooboo.Template.list({
            pageNr: pageNr,
          }).then(function (res) {
            if (res.success) {
              self.packages.list = [];
              self.$nextTick(function () {
                self.packages = res.model;
                self.cachedList = res.model;
              });
            }
          });
        }
      },
      changePersonalPackagesPage: function (pageNr) {
        window.scrollTo(0, 0);
        Kooboo.Template.personal({
          pageNr: pageNr,
        }).then(function (res) {
          if (res.success) {
            self.personalPackages.list = [];
            self.$nextTick(function () {
              self.personalPackages = res.model;
              self.cachePersonal = res.model;
            });
          }
        });
      },
      saveEdit: function () {
        var data = new FormData();

        data.append("id", self.editModel.id);
        data.append("isPrivate", self.editModel.isPrivate);
        data.append("category", self.editModel.category);
        data.append(
          "tags",
          $("#select2_element")
            .select2("data")
            .map(function (f) {
              return f.text.trim();
            })
            .join(",")
        );
        data.append("description", self.editModel.description || "");
        data.append("link", self.editModel.link || "");
        data.append(
          "images",
          JSON.stringify(
            self.editModel.images.map(function (f) {
              if (typeof f != "string") return f.file.name;
              return f;
            })
          )
        );

        self.editModel.images.forEach(function (f, index) {
          if (typeof f != "string") {
            data.append("file_" + index, f.file);
          }
        });

        if (self.editModel.file) {
          data.append("binary", self.editModel.file);
        }

        var selected = self.editModel.images[self.editModel.defaultImg];
        if (selected) {
          if (typeof selected == "string") {
            data.append("defaultImg", self.editModel.defaultImg);
          } else {
            var index = self.editModel.images
              .filter(function (f) {
                return typeof f != "string";
              })
              .indexOf(selected);
            data.append("defaultFile", index);
          }
        }

        Kooboo.Template.Update(data).then(function (res) {
          if (res.success) {
            publicTabNeedRefresh = true;
            Kooboo.Template.personal().then(function (r) {
              if (r.success) {
                self.searched = false;
                self.personalPackages.list = [];
                self.$nextTick(function () {
                  self.personalPackages = r.model;
                  self.cachePersonal = r.model;
                  self.showEditTemplateModal = false;
                });

                window.info.show(Kooboo.text.info.update.success, true);
              }
            });
          } else {
            window.info.show(Kooboo.text.info.update.fail, false);
          }
        });
      },
      loadImg: function () {
        setTimeout(function () {
          $("img.lazy").lazyload({
            event: "scroll",
            effect: "fadeIn",
          });
        }, 100);
      },
      chooseAsDefault: function (m) {
        self.editing.imgList.forEach(function (f) {
          f.selected(false);
        });
        m.selected(true);
      },
      removeFile: function (item, index) {
        var selected = self.editModel.images[self.editModel.defaultImg];
        self.editModel.images.splice(index, 1);
        if (index == self.editModel.defaultImg) {
          if (index > 0) self.editModel.defaultImg = index - 1;
          else self.editModel.defaultImg = 0;
        } else {
          self.editModel.defaultImg = self.editModel.images.indexOf(selected);
        }
      },
      uploadImg: function (data, files) {
        files.forEach(function (f) {
          var reader = new FileReader();
          reader.onloadend = function () {
            self.editModel.images.push({
              data: reader.result,
              file: f,
            });
          };
          reader.readAsDataURL(f);
        });
      },
      uploadFile: function (data, files) {
        self.editModel.file = files[0];
      },
    },
    watch: {
      packages: function () {
        this.loadImg();
      },
      personalPackages: function () {
        this.loadImg();
      },
      showEditTemplateModal: function (value) {
        if (value) {
          setTimeout(function () {
            $(".autosize").textareaAutoSize().trigger("keyup");
          }, 300);
        }
      },
    },
  });
</script>
